#include <iostream>
#include <pthread.h>
#include <unistd.h>

//模拟售票系统

//pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; //静态初始化互斥量
pthread_mutex_t mutex;
int gticket = 400;

void* routine(void* args)
{
    char* name = (char*)args;
    while(true)
    {
        //if语句也是非原子操作
        pthread_mutex_lock(&mutex); //加锁
        if(gticket > 0)
        {
            usleep(1000);
            printf("%s buys a ticket, there are %d tickets\n", name, gticket);
            gticket--; //非原子操作
            pthread_mutex_unlock(&mutex); //if路径的解锁
        }
        else
        {
            pthread_mutex_unlock(&mutex); //else路径的解锁
            break;
        }
    }
    return nullptr;
}

int main()
{
    pthread_mutex_init(&mutex, nullptr); //初始化锁
    pthread_t tid1, tid2, tid3, tid4;
    ::pthread_create(&tid1, nullptr, routine, (void*)"thread1");
    ::pthread_create(&tid2, nullptr, routine, (void*)"thread2");
    ::pthread_create(&tid3, nullptr, routine, (void*)"thread3");
    ::pthread_create(&tid4, nullptr, routine, (void*)"thread4");

    ::pthread_join(tid1, nullptr);
    ::pthread_join(tid2, nullptr);
    ::pthread_join(tid3, nullptr);
    ::pthread_join(tid4, nullptr);
    pthread_mutex_destroy(&mutex); //销毁锁
    return 0;
}